package com.qingshu.handle;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.qingshu.common.util.servlet.ServletUtils;
import com.qingshu.common.util.body.ResultCode;
import com.qingshu.common.util.body.ResultTool;
import com.qingshu.common.util.string.StringUtils;
import com.qingshu.common.entity.sys.model.LoginUser;
import com.qingshu.service.TokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import com.alibaba.fastjson.JSON;

/**
 * 自定义退出处理
 *
 * @author Huzz
 */
@Slf4j
@Configuration
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {
    @Autowired
    private TokenService tokenService;

    /**
     * 退出处理
     *
     * @return
     */
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser)) {
            String username = loginUser.getUsername();
            // 删除用户缓存记录
            tokenService.delLoginUser(loginUser.getToken());
            // TODO 记录用户退出日志
            //AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGOUT, "退出成功"));
        }
        log.info(loginUser.getUsername() + " 退出登录");
        ServletUtils.renderString(response, JSON.toJSONString(ResultTool.success(ResultCode.SUCCESS)));
    }
}
